<template>
	<textarea ref="editor"></textarea>
</template>
<script lang="ts">
import { ClassicEditor } from '@ckeditor/ckeditor5-editor-classic';
import { Essentials } from '@ckeditor/ckeditor5-essentials';
import { Autoformat } from '@ckeditor/ckeditor5-autoformat';
import { SimpleUploadAdapter } from '@ckeditor/ckeditor5-upload';
import { Image, ImageUpload, ImageCaption, ImageResize, ImageStyle, ImageToolbar } from '@ckeditor/ckeditor5-image';
import { Bold, Italic, Superscript, Subscript } from '@ckeditor/ckeditor5-basic-styles';
import { Paragraph } from '@ckeditor/ckeditor5-paragraph';
import { LinkImage } from '@ckeditor/ckeditor5-link';
import { Table, TableToolbar, TableCellProperties, TableProperties, TableColumnResize } from '@ckeditor/ckeditor5-table';
import '@ckeditor/ckeditor5-build-classic/build/translations/zh-cn'

let editor: any = null;

export default {
	props: {
		value: {
			type: String,
			default: ''
		}
	},
	data() {
		return {
			text: '' as string,
			ckConfig: {
				placeholder: '请输入内容',
				language: 'zh-cn',
				toolbar: ['undo', 'redo', 'bold', 'italic', 'superscript', 'subscript', 'imageUpload', 'insertTable'], 
				plugins: [ Table, TableToolbar, TableCellProperties, TableProperties, TableColumnResize, Essentials, Autoformat, Image, ImageToolbar, ImageCaption, ImageStyle, ImageResize, LinkImage, ImageUpload, Bold, Italic, Superscript, Subscript, Paragraph, SimpleUploadAdapter ],
				simpleUpload: {
					// The URL that the images are uploaded to.
					uploadUrl: import.meta.env.VITE_APP_BASE_API + '/file/editor',
					// Enable the XMLHttpRequest.withCredentials property.
					withCredentials: true,
					// Headers sent along with the XMLHttpRequest to the upload server.
					headers: {
						'X-CSRF-TOKEN': 'CSRF-Token',
						Authorization: 'Bearer <JSON Web Token>'
					}
				},
				image: {
					toolbar: [
						'imageStyle:inline', 'imageStyle:wrapText', 'imageStyle:breakText', '|',
						'toggleImageCaption', 'imageTextAlternative'
					]
				},
        table: {
          contentToolbar: [ 'tableColumn', 'tableRow', 'mergeTableCells', 'tableProperties', 'tableCellProperties' ]
        },
				width: '100%'
			}
		}
	},
	mounted() {
		ClassicEditor
			.create(this.$refs.editor, this.ckConfig)
			.then((neweditor: any) => {
				editor = neweditor
				neweditor.setData(this.value)
				editor.model.document.on('change:data', () => {
					this.text = neweditor.getData()
					this.$emit('update:value', this.text)
				});
			})
			.catch( (error: string) => {
				console.error( error )
			});
	},
	watch: {
		value(val: string){
			if(this.text !== val){
				editor.setData(val)
			}
		}
	}
}
</script>
<style>
.ck-editor__editable {
	max-height: 80vh;
}
</style>